package com.bfly.mall.advert.service.impl;

import com.bfly.common.page.Pager;
import com.bfly.common.util.StringUtil;
import com.bfly.core.base.service.BaseServiceImpl;
import com.bfly.core.context.PagerThreadLocal;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import com.bfly.mall.advert.dao.CouponGetRecordMapper;
import com.bfly.mall.advert.dto.CouponGetRecordListDTO;
import com.bfly.mall.advert.dto.CouponGetRecordUserListDTO;
import com.bfly.mall.advert.entity.Coupon;
import com.bfly.mall.advert.entity.CouponGetRecord;
import com.bfly.mall.advert.enums.CouponStatus;
import com.bfly.mall.advert.enums.CouponUseRange;
import com.bfly.mall.advert.enums.CouponUseStatus;
import com.bfly.mall.advert.service.ICouponGetRecordService;
import com.bfly.mall.advert.service.ICouponService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 长沙商脉科技有限公司
 * @date 2020/9/20 13:05
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class CouponGetRecordServiceImpl extends BaseServiceImpl<CouponGetRecord, Integer> implements ICouponGetRecordService {

    @Autowired
    private CouponGetRecordMapper couponGetRecordMapper;
    @Autowired
    private ICouponService couponService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receiveCoupon(int userId, int couponId) {
        Coupon coupon = couponService.get(couponId);
        if (coupon == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "不存在的优惠卷信息!");
        }
        CouponStatus status = CouponStatus.getStatus(coupon.getStatus());
        if (status != CouponStatus.ON_SHELF) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, String.format("优惠卷状态为 %s 不能领取!", status.getName()));
        }
        if (coupon.getRemaining() <= 0) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "优惠卷剩余数量不足,不能领取!");
        }
        int count = couponGetRecordMapper.getCouponUserCount(userId, couponId);
        if (count >= coupon.getLimitNum()) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, String.format("优惠卷每人限领 %s 张, 不能再次领取!", coupon.getLimitNum()));
        }

        // 保存领取记录
        Date start = new Date();
        Date end = DateUtils.addDays(start, coupon.getDays());

        CouponGetRecord couponGetRecord = new CouponGetRecord();
        couponGetRecord.setUserId(userId);
        couponGetRecord.setCouponId(couponId);
        couponGetRecord.setStatus(CouponUseStatus.NOT_USE.getId());
        couponGetRecord.setCode(generateCouponCode(coupon));

        couponGetRecord.setCreateDate(start);
        couponGetRecord.setStartDate(start);
        couponGetRecord.setEndDate(end);
        super.save(couponGetRecord);

        // 修改优惠卷剩余数量
        coupon.setRemaining(coupon.getRemaining() - 1);
        coupon.setUpdateDate(new Date());
        couponService.edit(coupon);
    }

    /**
     * 生成券码
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/12/1 12:30
     */
    private String generateCouponCode(Coupon coupon) {
        String code = "";
        CouponUseRange range = CouponUseRange.getRange(coupon.getUseRange());
        switch (range) {
            case ALL:
                code = "A";
                break;
            case PRODUCT:
                code = "P";
                break;
            case CATEGORY:
                code = "C";
                break;
        }
        while (true) {
            code += StringUtil.getRandomNumber(14);
            CouponGetRecordListDTO dto = couponGetRecordMapper.getUserCouponByCode(code);
            if (dto == null) {
                break;
            }
        }
        return code;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editStatus(int couponUserId, CouponUseStatus status) {
        if (status == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "用户优惠卷状态错误!");
        }
        CouponGetRecord couponGetRecord = super.get(couponUserId);
        if (couponGetRecord == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "不存在的用户优惠卷!");
        }
        couponGetRecord.setStatus(status.getId());
        couponGetRecord.setUpdateDate(new Date());
        super.edit(couponGetRecord);
    }

    @Override
    public List<CouponGetRecordListDTO> getUserCoupon(int userId, CouponUseStatus status) {
        return couponGetRecordMapper.getUserCoupon(userId, status == null ? null : status.getId());
    }

    @Override
    public Pager<CouponGetRecordUserListDTO> getCouponGetRecordForUser(int couponId) {
        Pager pager = PagerThreadLocal.get();
        long total = couponGetRecordMapper.getCouponGetRecordCountForUser(couponId);
        List<CouponGetRecordUserListDTO> list = couponGetRecordMapper.getCouponGetRecordForUser(couponId, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        Pager<CouponGetRecordUserListDTO> data = new Pager<>(pager.getPageNo(), pager.getPageSize(), total);
        data.setData(list);
        return data;
    }
}
